﻿using CefSharp;
using CefSharp.WinForms;
using Newtonsoft.Json;
using SmartForm;
using SmartForm.Common;
using SmartForm.NetJs;
using SmartForm.Rule;
using SmartlForm.DAL;
using SmartlForm.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmartlForm
{
    [ComVisible(true)]
    public partial class BowContainer : BaseForm
    {
        public ChromiumWebBrowser chromeBrowser;
        bool isConfirm = false, isCompleted = false;
        ChromeJs chromeJs;
        /// <summary>
        /// 任务完成委托
        /// </summary>
        /// <param name="topmost"></param>
        public delegate void CompletedDelegate();
        public CompletedDelegate Completed;//定义委托实例  
        public FormPar formPar;

        public BowContainer(string title = "窗口", string url = @"\page\pages\samples\error-404.html")
        {
            show(new FormPar() { title = title, url = url });
        }
        public BowContainer(string title = "窗口", string url = @"\page\pages\samples\error-404.html", bool display = true)
        {
            show(new FormPar() { title = title, url = url, display = display });
        }
        public BowContainer(FormPar formPar)
        {
            show(formPar);
        }

        public void show(FormPar formPar)
        {
            this.formPar = formPar;
            this.Name = formPar.name;
            this.Text = formPar.title;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.None;
            this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
            InitializeComponent();
            if (!formPar.display)
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                SetVisibleCore(false);
            }
            if (formPar.windowMin)
            {
                this.WindowState = FormWindowState.Minimized;
            }
            if (formPar.windowMax)
            {
                this.WindowState = FormWindowState.Maximized;
            }
            if (formPar.width > 0)
            {
                this.Width = formPar.width;
            }
            if (formPar.height > 0)
            {
                this.Height = formPar.height;
            }
            this.menu_max.Visible = formPar.max;
            this.menu_min.Visible = formPar.min;
            if (formPar.minWidth > 0 && formPar.minHeight > 0)
            {
                this.MinimumSize = new Size(formPar.minWidth, formPar.minHeight);
            }
            else
            {
                this.MinimumSize = new Size(400, 100);
            }
            this.head_title.Text = formPar.title;
            this.Text = formPar.title;
            if (formPar.name.Equals("sendForm"))
            {
                chromeBrowser = ChromeBrowserUtil.InitializeChromium(formPar.url, this.web_panel);
                chromeJs = new NetJs.BowContainer(chromeBrowser, this);
                CheckForIllegalCrossThreadCalls = false;
                chromeBrowser.RegisterJsObject("objectJS", chromeJs);


            }
            else
            {
                chromeBrowser = ChromeBrowserUtil.InitializeChromium(formPar.url, this.web_panel);
                chromeJs = new NetJs.BowContainer(chromeBrowser, this);
                CheckForIllegalCrossThreadCalls = false;
                chromeBrowser.RegisterJsObject("objectJS", chromeJs);
            }
        }


        private void BowContainer_Load(object sender, EventArgs e)
        {
            if (formPar.name.Equals("sendForm"))
            {
                startTask();
            }
        }

        public void startTask()
        {
            Console.WriteLine("formPar.data ：" + formPar.data);
            Send send = JsonConvert.DeserializeObject<Send>(formPar.data);
            List<SystemRule> systemRuleList = getSystemRuleList(send.title, send.content, send.type);
            Console.WriteLine("systemRuleList   ：" + systemRuleList.Count);

            if (systemRuleList != null)
            {
                foreach (var systemRule in systemRuleList)
                {
                    Console.WriteLine("systemRule 进入规则运行;" + systemRule.LoginUrl);
                    chromeBrowser.Load(systemRule.LoginUrl);
                    Delay.DelaySecond(5);
                    string js = string.Empty;
                    //登录账户密码
                    if (systemRule.LoginJS != null && systemRule.LoginJS.Count > 0)
                    {
                        foreach (var item in systemRule.LoginJS)
                        {
                            js = item.JS.Replace("$account", systemRule.Account).Replace("$password", systemRule.Password);
                            LogUtil.WriteLog(js);
                            if (item.JS.Contains("return "))
                            {
                                chromeJs.ExeScript(js);
                            }
                            else
                            {
                                chromeJs.ExeScriptResult(js);
                            }
                            if (item.Second > 0)
                            {
                                Delay.DelaySecond(item.Second);
                            }
                        }
                    }
                    //填写表单
                    foreach (var item in systemRule.FormOptionJSList)
                    {
                        Console.WriteLine("systemRule.FormOptionJSList：" + item.JS);
                        if (!string.IsNullOrEmpty(item.JS))
                        {
                            js = item.GetJS();
                            if (item.JS.Contains("return "))
                            {
                                chromeJs.ExeScript(js);
                            }
                            else
                            {
                                chromeJs.ExeScriptResult(js);
                            }
                        }
                        if (item.Second > 0)
                        {
                            Delay.DelaySecond(item.Second);
                        }
                    }
                    //更新发送次数
                    GroupDao.Instance.UpdateSendCount(NetJs.BowContainer.account.id);
                    //添加发送记录
                    TaskArticlePlatformDao.Instance.AddSendRecord(NetJs.BowContainer.account.id, systemRule);
                }
                Console.WriteLine("systemRule 结束规则运行");
            }
            Console.WriteLine("已全部发送完毕");
            MessageBox.Show("已全部发送完毕");
            chromeJs.ExeScript("objectJS.exit()");
        }

        /// <summary>
        /// 等待确认提交
        /// </summary>
        public void SubmitConfirmWait()
        {
            if (!isConfirm)
            {
                //等待确认提交
                Delay.DelaySecond(1);
                SubmitConfirmWait();
            }
        }

        public List<SystemRule> getSystemRuleList(string title, string content, string type)
        {
            if (string.IsNullOrEmpty(type))
            {
                return null;
            }
            List<SystemRule> systemRuleList = new List<SystemRule>();
            string[] types = type.Split(',');
            if (types.Contains("新浪微博"))
            {
                systemRuleList.Add(getWeiboRule(title, content));
            }
            if (types.Contains("今日头条"))
            {
                systemRuleList.Add(getToutiaoRule(title, content));
            }
            return systemRuleList;
        }

        /// <summary>
        /// 任务完成回调
        /// </summary>
        void TaskCompleted()
        {
            isCompleted = true;
        }

        /// <summary>
        /// 等待当前任务完成
        /// </summary>
        void WaitTaskCompleted()
        {
            if (!isCompleted)
            {
                Delay.DelaySecond(1);
                WaitTaskCompleted();
            }
        }

        private string getInputJs(string doc, string value)
        {
            return @"var o={0};o.focus();o.value=`{1}`;
            if ('createEvent' in document) {
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent('input', false, true);
                o.dispatchEvent(evt);
            } else {
			 	o.fireEvent('oninput');
			}
         ".Replace("{0}", doc).Replace("{1}", value);
        }

        private string getHtmlJs(string doc, string value)
        {
            return @"var o={0};o.focus();o.innerHTML=`{1}`;
            if ('createEvent' in document) {
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent('input', false, true);
                o.dispatchEvent(evt);
            } else {
			 	o.fireEvent('oninput');
			}
         ".Replace("{0}", doc).Replace("{1}", value);
        }




        /// <summary>
        /// 获取微博规则
        /// </summary>
        private SystemRule getWeiboRule(string title, string content)
        {
            SystemRule systemRule = new SystemRule();
            systemRule.Platform = "新浪微博";
            systemRule.LoginUrl = "https://weibo.com/";
            //系统规则
            systemRule.FormOptionJSList = new List<FormOptionJS>()
            {
                new FormOptionJS(){  JS="location.href='https://card.weibo.com/article/v3/editor';", Second = 5 },
                new FormOptionJS(){  JS="document.getElementsByClassName('bor')[0].click();", Second = 2 },
                new FormOptionJS(){  JS=getInputJs("document.getElementsByClassName('W_input W_input_focus')[0]",title),Name="Title", Value=title, Second = 2},
                new FormOptionJS(){  JS=getInputJs("document.getElementsByClassName('W_input_focus')[1]",title),Name="Title", Value=title, Second = 2},
                new FormOptionJS(){  JS=getHtmlJs("document.getElementsByClassName('WB_editor_iframe')[0]", "<p align='justify'>"+content+"</p>'"),Name="Content", Value=content, Second = 2},
                new FormOptionJS(){  JS="document.getElementsByClassName('W_btn_a')[0].click();", Value="下一步", Second = 2},
                new FormOptionJS(){  JS="document.getElementsByClassName('W_btn_a')[0].click();", Value="下一步", Second = 2},
                new FormOptionJS(){  JS="document.getElementsByClassName('W_btn_a')[1].click();", Value="发表按钮" , Second = 2},
                new FormOptionJS(){  Value="完成",Completed=true, Second = 5},
            };

            return systemRule;
        }


        /// <summary>
        /// 今日头条
        /// </summary>
        private SystemRule getToutiaoRule(string title, string content)
        {
            SystemRule systemRule = new SystemRule();
            systemRule.Platform = "今日头条";
            systemRule.LoginUrl = "https://www.toutiao.com/";
            //系统规则
            systemRule.FormOptionJSList = new List<FormOptionJS>()
            {
                new FormOptionJS(){    Second =3 },
                new FormOptionJS(){  JS="document.getElementsByClassName('checkbox-wrap')[0].click()", Second = 1 },
                new FormOptionJS(){  JS=getInputJs("document.getElementsByClassName('title-input long')[0]",content),Name="Content", Value=content, Second = 3},
                new FormOptionJS(){  JS="document.getElementsByClassName('upload-publish')[0].click()", Value="智能表单 - 发表按钮", Second = 2 },
                new FormOptionJS(){  Value="完成",Completed=true, Second = 5},
            };

            return systemRule;
        }
        #region winfrom UI 

        public override void app_Resize(object sender, EventArgs e)
        {
            base.app_Resize(sender, e);
        }

        public override void drag_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks > 1)
            {
                base.menu_max_Click(sender, e);
            }
            else
            {
                base.drag_MouseDown(sender, e);
            }
        }

        public override void menu_close_Click(object sender, EventArgs e)
        {
            this.Hide();
            if (chromeBrowser != null)
            {
                chromeBrowser.Dispose();
            }
            base.menu_close_Click(sender, e);
        }

        public override void menu_max_Click(object sender, EventArgs e)
        {
            base.menu_max_Click(sender, e);
        }

        public override void menu_min_Click(object sender, EventArgs e)
        {
            base.menu_min_Click(sender, e);
        }

        public override void menu_MouseHover(object sender, EventArgs e)
        {
            base.menu_MouseHover(sender, e);
        }

        public override void menu_MouseLeave(object sender, EventArgs e)
        {
            base.menu_MouseLeave(sender, e);
        }

        public override void menu_MouseMove(object sender, MouseEventArgs e)
        {
            base.menu_MouseMove(sender, e);
        }

        private void head_panel_DoubleClick(object sender, EventArgs e)
        {
            base.menu_max_Click(sender, e);
        }

        public override void line_Paint(object sender, PaintEventArgs e)
        {
            base.line_Paint(sender, e);
        }

        #endregion

        #region 窗体改变事件

        public override void Form_MouseDown(object sender, MouseEventArgs e)
        {
            base.Form_MouseDown(sender, e);
        }

        public override void Form_MouseUp(object sender, MouseEventArgs e)
        {
            base.Form_MouseUp(sender, e);
        }

        public override void Form_MouseMove(object sender, MouseEventArgs e)
        {
            base.Form_MouseMove(sender, e);
        }

        #endregion

    }
}
